<?php
if ($_GET['type'] != 4) {
    ?>
    <script type="text/javascript" src="/js/library/jqueryLib/jquery-1.10.0.min.js"></script>
    <script type="text/javascript" src="/js/library/jqueryLib/jquery-ui.js"></script>
    <!-- <script src="http://code.highcharts.com/highcharts.js"></script>
    <script src="http://code.highcharts.com/modules/exporting.js"></script> -->
    <script src="/js/functions/charts/highcharts.js"></script>
    <script src="/js/functions/charts/exporting.js"></script>
    <link rel="stylesheet" type="text/css" href="/css/jquery-ui.css">
    <?php
}


$auth = Auth::getAuth('current_user');
$db = new Database;
$fs = new functions;
$search = new Search();

/*added by aaron for page security*/
if(isset($_GET['form_id'])){
    $id = $_GET['form_id'];
    $obj = array("condition"=>" AND w.id = ". $id ." ");
    $obj = json_decode(json_encode($obj),true);
    $result = $search->getForms("",0,$obj);
    // print_r($result);
    $countForm = count($result);
    if($countForm==0){
        header("location:/user_view/home");
    }
}

$date = $fs->currentDateTime();
$application_id = $_COOKIE['application'];

$id = $_GET['id'];
$formId = $_GET['form_id'];
$keyword = $_GET['keyword'];
$type = $_GET['type'];
$chartFields = $_GET['chartFields'];
$chartDataType = $_GET['chartDataType'];

$reportDoc = new Report($db, $id);
$formDoc = new Form($db, $formId);

$parameters = json_decode($reportDoc->parameters, true);

$whereClause = '';


$parameters_array = array();
foreach ($parameters as $arr) {

    if ($whereClause != '') {
        $whereClause .= ' AND ';
    }

    if ($parameters_array[$arr['Field']] == '') {
        $parameters_array[$arr['Field']] = '0';
    } else {
        $parameters_array[$arr['Field']] = $parameters_array[$arr['Field']] + 1;
    }

    foreach ($arr as $key => $value) {
        if ($key == 'Field') {
            $field_value = $_GET[$value][$parameters_array[$arr['Field']]];
        }

        if ($key != 'Column') {

            if ($key == 'Operator' && $value == '%') {
                $whereClause .= ' LIKE ';
            } else {
                $whereClause .= ' ' . $value;
            }
        }

        if ($key == 'Operator') {

            if ($value == '%') {
                $whereClause .= " '%" . $field_value . "%' ";
            } else {
                $whereClause .= " '" . $field_value . "' ";
            }
        }
    }
}

//$columns = explode(",", $reportDoc->columns);

$columns = json_decode($reportDoc->columns, true);
//$strSQL = 'SELECT * FROM ' . $formDoc->form_table_name;
$strSQL = 'SELECT ID, TrackNo, Requestor, Processor, ' . $formDoc->active_fields . ' FROM ' . $formDoc->form_table_name;
//$strSQL = "SELECT ";
//foreach ($columns as $column) {
//    $strSQL.="'".$column['Value'] ."', "; 
//}
//$strSQL = substr($strSQL, 0, strlen($strSQL) - 2);
//
//$strSQL.=' FROM ' . $formDoc->form_table_name;
if ($whereClause != '') {
    $strSQL .= ' WHERE ' . $whereClause;
}


$sort_count = 0;
/*
  foreach ($columns as $column) {
  $colum_name = $column['Name'];

  $sort = $column['Sort'];
  if ($sort == "ascending") {
  $sort_count++;
  if ($sort_count == 1) {
  $strSQL.= " ORDER BY " . $colum_name . " ASC ";
  } else {
  $strSQL.= ", " . $colum_name . " ASC ";
  }
  }

  if ($sort == 'descending') {
  $sort_count++;
  if ($sort_count == 1) {
  $strSQL.= " ORDER BY " . $colum_name . " DESC ";
  } else {
  $strSQL.= ", " . $colum_name . " DESC ";
  }
  }
  }
 */

$result = $db->query($strSQL, "array");


$tableClass = "";
if ($type == 2) {
    $filename = $reportDoc->title . '_' . $date . '.xls';
    $filename = str_replace(" ", "_", $filename);
    header('Content-type: application/ms-excel');
    header('Content-Disposition: attachment; filename=' . $filename);
}


$ret = '<title>' . $reportDoc->title . '</title>';
$ret .= '<body style="font-family:Arial;font-size:12px">';
$ret .= '<h2 class="reportTitle">' . $reportDoc->title . '</h2>';
$ret .= '<label style="font-weight:Bold">Generated By:</label> ' . $auth['display_name'] . '<br/>';
$ret .= '<label style="font-weight:Bold">Date Generated:</label> ' . $date;

if ($type != 3) {

    $ret .= '<table id="' . $tableClass . '" style="margin-top:5px" cellpadding=5 cellspacing=0>';
    $ret .= '<tr>';

    foreach ($columns as $column) {
        $ret .= '<th style="font-size:12px;background: #4590D2;border:1px Solid #ccc;color:#fff;width:' . $column['Width'] . '">' . $column['Name'] . '</th>';
    }
    $ret .= '</tr>';

    $tmp_category = array();
    $pdf_data = array();
    $pdf_data_row = array();
    $total = array();
    $total_index = 0;
    $average_index = 0;
    foreach ($result as $row) {
        $ret .= '<tr>';

        $columnIndex = 0;
        foreach ($columns as $column) {
            if ($column['ValueType'] == 'static') {
                $column_value = $column['Value'];
            } else {
                $formulaDoc = new Formula($column['Value']);
                $formulaDoc->setSourceForm($formDoc->form_name, "*", array(
                    array("FieldName" => "ID",
                        "Operator" => "=",
                        "Value" => $row['ID'])
                        )
                );

                $column_value = $formulaDoc->evaluate();
            }

            if ($column['Group'] == "categorized") {
                if (!$tmp_category[$column['Name']]) {
                    $tmp_category[$column['Name']] = $column_value;
                } else {
                    if ($tmp_category[$column['Name']] != $column_value) {
                        $tmp_category[$column['Name']] = $column_value;
                    } else {
                        //$column_value = "";
                        continue 2;
                    }
                }
            }

            $alignment = 'text-align:left';

            //show total
            if ($column['ShowTotal'] == 'true') {
                $total_index++;
                $total[$column['Name']] = $total[$column['Name']] + $column_value;
            }

            if ($column['ShowAverage'] == 'true') {
                $average_index++;
            }

            //if ($column['Format'] == 'Currency') {
            //    $column_value = number_format($column_value, 2);
            //    $alignment = 'text-align:right';
            //}
            //
            //if ($column['Format'] == 'Number') {
            //    $alignment = 'text-align:right';
            //}



            if ($columnIndex == 0) {
            //    $ret .= '<td style="font-size:12px;border:1px Solid #ccc;' . $alignment . '"><a href="/workspace?view_type=request&formID=' . $formDoc->id . '&requestID=' . $row['ID'] . '&trackNo=' . $row['TrackNo'] . '">' . $column_value . '</td>';
            } else {
            //    $ret .= '<td style="font-size:12px;border:1px Solid #ccc;' . $alignment . '">' . $column_value . '</td>';
            }

            $pdf_data_row[$column['Name']] = $column_value;

            $columnIndex++;
        }

        array_push($pdf_data, $pdf_data_row);
        $ret .= '</tr>';
    }

    $pdf_data = functions::my_array_unique($pdf_data);
    
    foreach($pdf_data as $pdf_row){
        $ret .= '<tr>';
        $columnIndex = 0;
        
        foreach($pdf_row as $column_value){
            $alignment = '';
            if (is_numeric($column_value)) {
                $column_value = number_format($column_value, 2);
                $alignment = 'text-align:right';
            }
            
            if ($columnIndex == 0) {
                $ret .= '<td style="font-size:12px;border:1px Solid #ccc;' . $alignment . '"><a href="/user_view/workspace?view_type=request&formID=' . $formDoc->id . '&requestID=' . $row['ID'] . '&trackNo=' . $row['TrackNo'] . '">' . $column_value . '</td>';
            } else {
                $ret .= '<td style="font-size:12px;border:1px Solid #ccc;' . $alignment . '">' . $column_value . '</td>';
            }
            $columnIndex++;
        }
        $ret .= '</tr>';
    }
    $total_Average = $total;
    //show total
    if ($total_index != 0) {
        $ret .= '<tr>';
        foreach ($columns as $column) {
            //show total

            if ($column['Format'] == 'Currency') {
                $total[$column["Name"]] = number_format($total[$column["Name"]], 2);
            }

            if ($column['ShowTotal'] == 'true') {
                $ret .= '<td style="font-size:12px;border:1px Solid #ccc;text-align:right"> <b>Total: </b>' . $total[$column["Name"]] . '</td>';
            } else {
                $ret .= '<td style="font-size:12px;border:1px Solid #ccc;text-align:right"></td>';
            }
        }
        $ret .= '</tr>';
    }

    //show average
    if ($average_index != 0) {
        $ret .= '<tr>';
        foreach ($columns as $column) {
            //show average
            if ($column['ShowAverage'] == 'true') {
                $total_Average[$column['Name']] = $total_Average[$column['Name']] / count($result);
                if ($column['Format'] == 'Currency') {
                    $total_Average[$column['Name']] = number_format($total_Average[$column['Name']], 2);
                }

                $ret .= '<td style="font-size:12px;border:1px Solid #ccc;text-align:right"> <b>Average: </b>' . $total_Average[$column['Name']] . '</td>';
            } else {
                $ret .= '<td style="font-size:12px;border:1px Solid #ccc;text-align:right"></td>';
            }
        }
        $ret .= '</tr>';
    }

    $ret .= '</table>';
    $ret .= '</body>';

//    if ($type != 4 && $type != 3) {
//        //create pdf
//        ob_end_clean();
//        header("Content-Encoding: None", true);
//        $pdfDoc = new Report_PDF();
//        $pdfDoc->AliasNbPages();
//        $pdfDoc->AddPage('L');
//        $pdfDoc->setHeader('', $reportDoc->title);
//        $pdfDoc->setContent($columns, $pdf_data);
//
//
//        $pdfDoc->Output();
//        return;
//    }
//    $tmp_category = array();
//    $column_ctr = 0;
//    foreach ($result as $row) {
//
//        do {
//
//            
//            $column_name = $columns[$column_ctr]['Name'];
//            $column_group = $columns[$column_ctr]['Group'];
//            $column_ctr++;
//        } while ($column_group == 'categorized');
//    }
}

if ($type == 4) {
    $filename = $reportDoc->title . '_' . $date . '.csv';
	$filename = str_replace(" ", "_", $filename);
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=' . $filename);

    // create a file pointer connected to the output stream
    $output = fopen('php://output', 'w');
    foreach ($result as $row) {
        fputcsv($output, $row);
    }

    fclose($output);
    return;
} else {
    echo $ret;
}

// for chart
if ($type == 3) {
    echo '<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>';
    echo '<input type="text" style="display:none" id="chart-type" value="' . $_GET['chartType'] . '"/>';
    echo '<input type="text" style="display:none" id="series" value="' . $_GET['series'] . '"/>';
    echo '<input type="text" style="display:none" id="yaxis" value="' . $_GET['yaxis'] . '"/>';
    echo '<input type="text" style="display:none" id="chartDataType" value="' . $chartDataType . '"/>';
}

$symbol_data = json_decode($reportDoc->symbol, true);
$whole_chart_data = array();

if ($chartDataType == 1) {
    $active_fields = split(",", $_GET['chartFields']);

    foreach ($active_fields as $field) {
        $values = $db->query("SELECT DISTINCT(" . $field . ") as Field_Value FROM " . $formDoc->form_table_name . " WHERE " . $whereClause, "array");
        $value_row = array();

        foreach ($values as $key => $value) {
            $isMultiple = strpos($value["Field_Value"], '|^|');

            if ($isMultiple) {

                $field_value_arr = explode('|^|', $value["Field_Value"]);

                foreach ($field_value_arr as $field_value_row) {
                    $valueCount = $db->query("SELECT COUNT(*) as ValueCount  FROM " . $formDoc->form_table_name . " WHERE " . $field . " LIKE '%" . $field_value_row . "%' AND " . $whereClause, "row");

                    array_push($value_row, array("FieldValue" => $field_value_row,
                        "Count" => $valueCount["ValueCount"]));
                }
            } else {
                if ($field == "Requestor" || $field == "Processor") {
                    $valueCount = $db->query("SELECT COUNT(*) as ValueCount  FROM " . $formDoc->form_table_name . " WHERE " . $field . " = {$db->escape($value["Field_Value"])} AND " . $whereClause, "row");

                    $personDoc = new Person($db, $value["Field_Value"]);
                    array_push($value_row, array("FieldValue" => $personDoc->display_name,
                        "Count" => $valueCount["ValueCount"]));
                } else {
                    $valueCount = $db->query("SELECT COUNT(*) as ValueCount  FROM " . $formDoc->form_table_name . " WHERE " . $field . " LIKE '%" . $value["Field_Value"] . "%' AND " . $whereClause, "row");

                    array_push($value_row, array("FieldValue" => $value["Field_Value"],
                        "Count" => $valueCount["ValueCount"]));
                }
            }
        }

        array_push($whole_chart_data, array("Column_Name" => $field,
            "Data" => $value_row));
    }
} else {
    $series = $_GET['series'];
    $versus = $_GET['versus'];

    $values = $db->query("SELECT DISTINCT(" . $versus . ") as Versus FROM " . $formDoc->form_table_name . " WHERE " . $whereClause, "array");

    foreach ($values as $value) {
        // $seriesArr = $db->query("SELECT COUNT(DISTINCT {$series}) as Series, {$series}  FROM " . $formDoc->form_table_name . " WHERE " . $versus . " = {$db->escape($value["Versus"])} AND " . $whereClause, "array");
        $seriesArr = $db->query("SELECT main.{$series} as Series, (
SELECT COUNT(item.{$series}) FROM " . $formDoc->form_table_name . " item WHERE item.{$series} = main.{$series} AND item.{$versus} = main.{$versus}
) as Count, main.* FROM " . $formDoc->form_table_name . " main WHERE {$versus} = {$db->escape($value["Versus"])} AND " . $whereClause . " GROUP BY main.{$series}", "array");

        $value_row = array();
        foreach ($seriesArr as $seriesRow) {

            if ($symbol_data["ValueType"] == "computed") {
                $formulaDoc = new Formula($symbol_data["Value"]);
                $formulaDoc->DataFormSource[0] = $seriesRow;
                $withSymbol = $formulaDoc->evaluate();
            } else {
                $withSymbol = true;
            }
            
            $withSymbol = false;

            if ($series == 'Requestor' || $series == 'Processor') {
                $personDoc = new Person($db, $seriesRow["Series"]);
                array_push($value_row, array("FieldValue" => $personDoc->display_name,
                    "Count" => $seriesRow["Count"],
                    "WithSymbol" => $withSymbol));
            } else {
                array_push($value_row, array("FieldValue" => $seriesRow["Series"],
                    "Count" => $seriesRow["Count"],
                    "WithSymbol" => $withSymbol));
            }
        }

        //merge duplicates
        $field_value = 0;
        $field_count = 0;
        $filed_symbol = 0;
        foreach($value_row as $value_data){
            $field_value+=$value_data["FieldValue"];
            $field_count=$value_data["Count"];
            $filed_symbol=$value_data["WithSymbol"];
        }
        $value_row = array();
        array_push($value_row,array("FieldValue" => $field_value,
                    "Count" => $field_count,
                    "WithSymbol" => $filed_symbol));
        //end
       
        if ($versus == 'Requestor' || $versus == 'Processor') {
            $personDoc = new Person($db, $value["Versus"]);
            array_push($whole_chart_data, array("Column_Name" => $personDoc->display_name,
                "Data" => $value_row));
        } else {
            array_push($whole_chart_data, array("Column_Name" => $value["Versus"],
                "Data" => $value_row));
        }
    }
}
//set plotbands
$plotbands_arr = json_decode($reportDoc->plotbands, true);
$chart_plot_bands = array();

foreach ($plotbands_arr as $key => $plot) {
    if ($plot["FromType"] == 'static') {
        $from = $plot["From"];
    } else {
        $formulaPlotDoc = new Formula($plot["From"]);
        $from = $formulaPlotDoc->evaluate();
    }

    if ($plot["ToType"] == 'static') {
        $to = $plot["To"];
    } else {
        $formulaPlotDoc = new Formula($plot["To"]);
        $to = $formulaPlotDoc->evaluate();
    }

    $array_plot = array(
        "from" => $from,
        "to" => $to,
        "color" => $plot["Color"],
        "label" => array(
            "text" => $plot["Name"],
            "style" => array("color" => "#606060"))
    );

    array_push($chart_plot_bands, $array_plot);
}


//echo "<input type='text' style='display:none' id='chart-data' value='" . json_encode($whole_chart_data) . "'/>";
echo "<div style='display:none' id='chart-data'>" . json_encode($whole_chart_data) . "</div>";
?>
<?php
if ($type == 3) {
    //if report type is chart
    ?>
    <div style='display:none'>
        <label>Y-Axis Max</label>
        <input id="yaxisMax" type="number" value="<?php echo $reportDoc->yaxis_max; ?>"/>
        <!--<div id="slider"></div>-->
        <label>Y-Axis Min</label>
        <input id="yaxisMin" type="number" value="<?php echo $reportDoc->yaxis_min; ?>"/>
        <label>Y-Axis Interval</label>
        <input id="yaxisInterval" type="number" value="<?php echo $reportDoc->yaxis_interval; ?>"/>
    </div>
    <div id="plot-bands-report-data" style="display: none"><?php echo json_encode($chart_plot_bands); ?></div>
    <?php
}
?>
<button class="pinit icon dataTip dashboard_pin" fl-data-application-id="<?php echo $application_id; ?>">Pin this to Dashboard</button>
<table id="chart-table" style="margin-top:5px;display:none" cellpadding=5 cellspacing=0>
    <thead>
        <tr class="series">
            <th style="font-size:12px;background: #4590D2;border:1px Solid #ccc;color:#fff"></th>
        </tr>
    </thead>
    <tbody class="data">
    </tbody>
</table>

<!-- <table id="" style="margin-top:5px" cellpadding=5 cellspacing=0>
    <thead>
        <tr>
            <th  style="font-size:12px;background: #4590D2;border:1px Solid #ccc;color:#fff"></th>
            <th  style="font-size:12px;background: #4590D2;border:1px Solid #ccc;color:#fff">Jane</th>
            <th  style="font-size:12px;background: #4590D2;border:1px Solid #ccc;color:#fff">John</th>
        </tr>
    </thead>
    <tbody>
        <tr style="font-size:12px;border:1px Solid #ccc">
            <th>Apples</th>
            <td>3</td>
            <td>4</td>
        </tr>
        <tr style="font-size:12px;border:1px Solid #ccc">
            <th>Pears</th>
            <td>2</td>
            <td>0</td>
        </tr>
        <tr style="font-size:12px;border:1px Solid #ccc">
            <th>Plums</th>
            <td>5</td>
            <td>11</td>
        </tr>
        <tr style="font-size:12px;border:1px Solid #ccc">
            <th>Bananas</th>
            <td>1</td>
            <td>1</td>
        </tr>
        <tr style="font-size:12px;border:1px Solid #ccc">
            <th>Oranges</th>
            <td>2</td>
            <td>4</td>
        </tr>
    </tbody>
</table> -->
<script type="text/javascript">
    $(document).ready(function() {
        $('body').on('change', '#yaxisMax, #yaxisMin, #yaxisInterval', function() {
            //chart.generateChart();
            var thisId = $(this).attr('id');
            var thisVal = $(this).val();
            var currentLocation = String(window.location);

            window.location = currentLocation + '&' + thisId + '=' + thisVal;

        });

<?php
if ($type == 3) {
    ?>
            chart.genereteTable();
    <?php
}
?>
        pin.init();
    });

    var pin = {
        init: function() {
            this.addEventListeners();
        },
        addEventListeners: function() {
            var self = this;
            $('body').on('click', '.dashboard_pin', function() {
                var pin = this;
                var content = [];

                content.push({
                    object_type: "report",
                    object_id: "<?php echo $reportDoc->title; ?>",
                    formId: "<?php echo $formDoc->id; ?>",
                    reportId: "<?php echo $reportDoc->id; ?>",
                    url: String(window.location)
                });

                self.save({
                    application_id: $(this).attr('fl-data-application-id'),
                    content: JSON.stringify(content)
                }, function(result) {
                    console.log(result);
                    alert('Content has been pinned.');
                    //$(pin).css('opacity', '.4');
//                showNotification({
//                    message: "Panel s.",
//                    type: "success",
//                    autoClose: true,
//                    duration: 3
//                });
                });
            });
        },
        save: function(data, callback) {
            $.get('/ajax/dashboard', data, function() {
                callback(data);
            });
        }
    }


    var chart = {
        genereteTable: function() {
            var chartData = $("#chart-data").text();
            chartData = JSON.parse(chartData);
            console.log(chartData);
            var startCell = 0;
            var endCell = 0;
            var headers = [];
            //set header and fields//
            for (var index in chartData) {

                var columnName = chartData[index].Column_Name;
                var data = chartData[index].Data;

                if (columnName != '' && columnName != null) {
                    var valueRow = '<tr id="tr_' + columnName.replace(/ /g, '_') + '" data-id="tr_' + columnName.replace(/ /g, '_') + '" style="font-size:12px;border:1px Solid #ccc"><th>' + columnName + '</th></tr>';
                    $('.data').append(valueRow);
                    for (var row in data) {
                        var columnHeader = data[row].FieldValue;
                        var withSymbol = data[row].WithSymbol;
                        if (headers.indexOf(columnHeader) == -1) {
                            headers.push(columnHeader);
                            $('.series').append('<th style="font-size:12px;background: #4590D2;border:1px Solid #ccc;color:#fff" symbol="' + withSymbol + '">' + columnHeader + '</th>');
                        }
                    }
                }
            }
            //data
            for (var index in chartData) {
                var columnName = chartData[index].Column_Name;
                var data = chartData[index].Data;
                var seriesCount = $('.series').find('th').length;


                if (columnName != '' && columnName != null) {

                    for (var ctr = 0; ctr <= headers.length - 1; ctr++) {
                        $('[data-id="tr_' + columnName.replace(/ /g, '_') + '"]').append('<td>0</td>');
                    }

                    for (var row in data) {
                        var count = data[row].Count;
                        var columnHeader = data[row].FieldValue;

                        var position = headers.indexOf(columnHeader) + 1;
                        $('[data-id="tr_' + columnName.replace(/ /g, '_') + '"]').children().eq(position).text(count);
                    }

                }

            }
            this.generateChart();
        }, getLineAreaSeries: function() {
            var data = [];
            $('#chart-table').find('.data th').each(function() {
                data.push($(this).text());
            });

            return data;
        }, getLineAreaData: function() {
            var data = [];
            $('#chart-table').find('.series th').each(function(index) {
                if (index > 0) {
                    if (parseInt($(this).text())) {
                        if ($(this).attr('symbol') == "true") {
                            data.push({
                                y: parseInt($(this).text()),
                                marker: {
                                    symbol: 'url(https://www.multimediasystems.co.uk/acatalog/Flashing-Circle.gif)'}
                            });
                        } else {
                            data.push({
                                y: parseInt($(this).text())
                            });
                        }

                    } else {
                        data.push({
                            y: parseInt($(this).text())
                        });
                    }
                    ;
                }
            });

            return data;
        }, getDataType: function() {
            var dataType = 'String';
            $('#chart-table').find('.series th').each(function(index) {
                if (index > 0) {
                    if (parseInt($(this).text())) {
                        dataType = 'Float';
                    }
                }
            });

            return dataType;
        }, generateChart: function() {
            var self = this;
            var chartType = $("#chart-type").val();
            var chartDataType = $('#chartDataType').val();
            var yaxis = $('#yaxis').val();
            var reportTitle = $(".reportTitle").text();
            var yAxisMax = $('#yaxisMax').val();
            var yAxisMin = $('#yaxisMin').val();
            var yAxisInverval = $('#yaxisInterval').val();
            var series = $("#series").val();
            var plotBands = JSON.parse($('#plot-bands-report-data').html());

            console.log('Plot Bands', plotBands);
            Highcharts.visualize = function(table, options) {
                // the categories
                options.xAxis.categories = [];
                $('tbody th', table).each(function(i) {
                    options.xAxis.categories.push(this.innerHTML);
                });

                // the data series
                options.series = [];
                $('tr', table).each(function(i) {
                    var tr = this;
                    $('th, td', tr).each(function(j) {
                        if (j > 0) { // skip first column
                            if (i == 0) { // get the name and init the series
                                options.series[j - 1] = {
                                    name: this.innerHTML,
                                    data: []
                                };
                            } else { // add values
                                options.series[j - 1].data.push(parseFloat(this.innerHTML));
                            }
                        }
                    });
                });

                var chart = new Highcharts.Chart(options);
            }

            if (chartDataType == 2 && yaxis != 0) {
                var chart = $('#container').highcharts({
                    chart: {
                        type: chartType
                    },
                    title: {
                        text: reportTitle,
                        x: -20 //center
                    },
                    xAxis: {
                        categories: self.getLineAreaSeries()
                    },
                    yAxis: {
                        min: parseInt(yAxisMin),
                        max: parseInt(yAxisMax),
                        tickInterval: parseInt(yAxisInverval),
                        plotLines: [{
                                value: 0,
                                width: 1,
                                color: '#808080'
                            }],
                        plotBands: plotBands
                    },
                    tooltip: {
                        valueSuffix: ''
                    },
                    series: [{
                            name: series,
                            data: self.getLineAreaData()
                        }]
                });

                console.log('chart data', {
                    chart: {
                        type: chartType
                    },
                    title: {
                        text: reportTitle,
                        x: -20 //center
                    },
                    xAxis: {
                        categories: self.getLineAreaSeries()
                    },
                    yAxis: {
                        min: parseInt(yAxisMin),
                        max: parseInt(yAxisMax),
                        tickInterval: parseInt(yAxisInverval),
                        plotLines: [{
                                value: 0,
                                width: 1,
                                color: '#808080'
                            }],
                        plotBands: plotBands
                    },
                    tooltip: {
                        valueSuffix: ''
                    },
                    series: [{
                            name: series,
                            data: self.getLineAreaData()
                        }]
                });
            } else {
                var table = document.getElementById('chart-table'),
                        options = {
                            chart: {
                                renderTo: 'container',
                                type: chartType
                            },
                            title: {
                                text: reportTitle
                            },
                            xAxis: {
                            },
                            yAxis: {
                                title: {
                                    text: 'Number of Record'
                                }
                            },
                            tooltip: {
                                formatter: function() {
                                    return '<b>' + this.series.name + '</b><br/>' +
                                            this.y + ' ' + this.x.toLowerCase();
                                }
                            }
                        };

                Highcharts.visualize(table, options);
            }
        }
    }

</script>